package site.huoqiang.emos.task;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import site.huoqiang.emos.exception.EmosException;
import site.huoqiang.emos.mapper.MeetingMapper;
import site.huoqiang.emos.mapper.UserMapper;

import java.util.HashMap;

/**
 * @author: huoqiang huoqiang
 * @date: 2022-03-04
 */
@Component
@Slf4j
public class MeetingWorkflowTask {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MeetingMapper meetingMapper;

    @Value("${emos.recieveNotify}")
    private String receiveNotify;

    @Value("${emos.code}")
    private String code;

    @Value("${emos.tcode}")
    private String tcode;

    @Value("${workflow.url}")
    private String workflow;

    /**
     * 开启会议工作流
     *
     * @param uuid        会议uuid
     * @param creatorId   创建人Id
     * @param title       会议标题
     * @param date        会议日期
     * @param start       会议开始时间
     * @param meetingType 会议类型
     */
    @Async("AsyncTaskExecutor")
    public void startMeetingWorkflow(String uuid, int creatorId, String title, String date, String start, String meetingType) {

        // 查询申请人基本信息
        HashMap info = userMapper.searchUserInfo(creatorId);

        // 创建JSONObject对象，保存提交的数据
        JSONObject json = new JSONObject();
        json.set("url", receiveNotify);
        json.set("uuid", uuid);
        json.set("creatorId", creatorId);
        json.set("creatorName", info.get("name").toString());
        json.set("code", code);
        json.set("tcode", tcode);
        json.set("title", title);
        json.set("date", date);
        json.set("start", start);
        json.set("meetingType", meetingType);

        // 判断申请的人角色是否包含总经理
        String[] roles = info.get("roles").toString().split(",");
        // 不包含总经理的话， 则获取总经理的userId和部门经理userId
        if (!ArrayUtil.contains(roles, "总经理")) {
            // 查询部门经理Id
            Integer managerId = userMapper.searchDeptManagerId(creatorId);
            json.set("managerId", managerId);

            // 查询总经理Id
            Integer gmId = userMapper.searchGmId();
            json.set("gmId", gmId);

            boolean bool = meetingMapper.searchMeetingMembersInSameDept(uuid);
            json.set("sameDept", bool);
        }

        // 发送请求
        String url = workflow + "/workflow/startMeetingProcess";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString()).execute();
        if (resp.getStatus() == 200) {
            json = JSONUtil.parseObj(resp.body());
            String instanceId = json.getStr("instanceId");
            // 更新会议记录的instance_id
            HashMap<Object, Object> param = new HashMap<>();
            param.put("uuid", uuid);
            param.put("instanceId", instanceId);
            int row = meetingMapper.updateMeetingInstanceId(param);

            if (row != 1) {
                throw new EmosException("保存会议工作流实例ID失败");
            }
        } else {
            log.error(resp.body());
        }
    }

    /**
     * 关闭会议工作流
     *
     * @param uuid       会议uuid
     * @param instanceId 工作流id
     * @param reason     关闭原因
     */
    @Async("AsyncTaskExecutor")
    public void deleteMeetingApplication(String uuid, String instanceId, String reason) {
        JSONObject json = new JSONObject();
        json.set("uuid", uuid);
        json.set("instanceId", instanceId);
        json.set("code", code);
        json.set("tcode", tcode);
        json.set("type", "会议申请");
        json.set("reason", reason);

        String url = workflow + "/workflow/deleteProcessById";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString()).execute();
        if (resp.getStatus() == 200) {
            log.debug("删除了会议申请");
        } else {
            log.error(resp.body());
        }
    }

}
